import Axios from 'axios'
import md5 from 'md5'
import store from 'store'
import message from 'ant-design-vue/es/message'
import Util from '@/common/util'

import { VERSION_NO, APP_KEY, REQUEST_INTEFACE_URL } from '@/common/config'

const requestHeads = () => {
  const timeStamp = new Date().getTime()
  let uuid = Util.getUUID()
  let parma = {
    'appKey': APP_KEY,
    'version': VERSION_NO,
    'timestamp': timeStamp,
    'nonce': uuid,
    'token': store.get('token') ? store.get('token') : '',
    'sign': md5(`appKey${APP_KEY}nonce${uuid}timestamp${timeStamp}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase()
  }
  return parma
}

const axiosInstatnce = Axios.create({
  baseURL: REQUEST_INTEFACE_URL,
  timeout: 60000,
  headers: {
    'appKey': APP_KEY,
    'version': VERSION_NO
  }
})

const err = (error) => {
  // console.log('err: ', error)
  message.error('请求失败，请检查服务')
  return Promise.reject(error)
}

axiosInstatnce.interceptors.request.use(function (config) {
  const timeStamp = new Date().getTime()
  let uuid = Util.getUUID()

  config.headers['timestamp'] = timeStamp
  config.headers['nonce'] = uuid
  config.headers['token'] = store.get('token') ? store.get('token') : ''
  config.headers['sign'] = md5(`appKey${APP_KEY}nonce${uuid}timestamp${timeStamp}84001ac0d7064aea883e8f6623ceb82b`).toUpperCase()
  // config.headers['powerId'] = Vue.prototype.powerId
  return config
}, err)

axiosInstatnce.interceptors.response.use((response) => {
  let rspStatus = response.status
  // console.log(response.request.responseURL + ' 请求返回状态：' + rspStatus)
  let responseObj = JSON.parse(response.config.data)

  if (rspStatus === 200) {
    if (response.config.responseType === 'blob' || response.config.responseType === 'arraybuffer') {
      let blob
      if (responseObj.fileType === 'zip') {
        blob = new Blob([response.data], { type: 'application/zip' })
      } else { // 默认excel
        blob = new Blob([response.data], { type: 'application/vnd.ms-excel;charset=utf-8' }) // application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
      }
      let downloadElement = document.createElement('a')
      let href = window.URL.createObjectURL(blob) // 创建下载的链接
      downloadElement.href = href
      // 获取文件名
      let fileName = '导出excel' + new Date().getTime() // 处理文件名乱码问题
      const disposition = response.headers['content-disposition']
      if (disposition) {
        const f = disposition.split('=')
        if (f && f.length > 1) {
          fileName = decodeURI(f[1])
        }
      }

      downloadElement.download = fileName // 下载后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 点击下载
      document.body.removeChild(downloadElement) // 下载完成移除元素
      window.URL.revokeObjectURL(href) // 释放掉blob对象
      return
    }
    if (response.data.code === 0) {

    } else if (response.data.code === -1 && response.data.errorCode === '9999') { // 多系统token混乱时候，退出登录
      store.remove('token')
      window.location.href = ('/user/login')
    } else {
      message.error(response.data.message)
      return Promise.reject(response.data)
    }
  } else {
    return Promise.reject(response.data)
  }

  return response.data
}, err)

// 请求
export const api = (uri, data) => axiosInstatnce.post(uri, data)

// 导出excel(.xls)
export const commonExport = (uri, data) => {
  const columns = data.columns || []
  if (columns.length > 0) {
    let excelTitleList = []
    let excelKeyList = []
    columns.forEach(v => {
      if (v.dataIndex) {
        excelTitleList.push(v.title)
        if (v._needName) { // 比如status字段，传statusName
          excelKeyList.push(`${v.dataIndex}Name`)
        } else {
          excelKeyList.push(v.dataIndex)
        }
      }
    })
    data['excelTitleList'] = excelTitleList
    data['excelKeyList'] = excelKeyList
    delete data.columns
  }
  axiosInstatnce.post(uri, data, { responseType: 'blob' })
}

// 上传excel1
export const importFile = data => axiosInstatnce.post('/bill/importAccountDetail', data, { 'ContentType': 'multipart/form-data' })

export default requestHeads
